Skip to content →

使用 Python 按文件扩展名对目录中的文件进行排序

这是一个python 脚本,它按文件扩展名对目录中的文件进行排序
将待排序的目录和待排序的文件结尾作为输入参数。
例如,该脚本对于在随着时间的推移不断增长的下载文件夹中创建顺序非常有帮助。

该脚本首先检查指定的目录是否有效。如果是,它遍历目录中的所有文件并检查它们的文件扩展名。如果文件扩展名是输入参数中指定的文件后缀之一,则文件将移动到以文件扩展名命名的子文件夹中。如果子文件夹尚不存在,则创建该子文件夹

import os
import shutil
def sort_files_by_extension(directory, file_endings):
"""
Sorts the files in the specified directory by file extension.
Arguments:
- directory: The path of the directory to be sorted
- file_endings: A list of file endings to be sorted
"""
# Check if the directory is valid
if not os.path.isdir(directory):
print(f"{directory} is not a valid directory.")
return
# Keep track of the number of files moved per file extension
files_moved = {}
# Keep track of the number of files not moved in the directory
files_not_moved = 0
# Iterate through all the files in the directory
for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
# Check if the file is a regular file
if os.path.isfile(file_path):
file_extension = os.path.splitext(filename)[1]
# Check if the file extension is one of the file endings to be sorted
if file_extension in file_endings:
subfolder = os.path.join(directory, file_extension[1:].upper())
# Create the subfolder if it doesn't exist yet
if not os.path.exists(subfolder):
os.makedirs(subfolder)
# Move the file to the subfolder
shutil.move(file_path, os.path.join(subfolder, filename))
# Increase the count of files moved for this file extension
files_moved[file_extension] = files_moved.get(file_extension, 0) + 1
else:
# Increase the count of files not moved
files_not_moved += 1
# Print the number of files moved per file extension
print("Files moved:")
for file_extension, count in files_moved.items():
print(f"{file_extension}: {count}")
# Print the number of files not moved
print(f"Files not moved: {files_not_moved}")
# Get the directory to be sorted
directory = input("Enter the directory path: ")
# Get the file endings to be sorted
file_endings = [x.strip() for x in input("Enter the file endings to sort (comma-separated): ").split(',')]
# Call the function to sort the files
sort_files_by_extension(directory, file_endings)

此脚本跟踪files_moved字典中每个文件扩展名移动的文件数。它还在files_not_moved变量中跟踪目录中未移动的文件数。在脚本的末尾,它打印出每个文件扩展名移动的文件数和目录中未移动的文件数。

您可以从我的 github 存储库下载源代码:

https://github.com/smartDevel/fileSorter

Click to rate this post!
[Total: 0 Average: 0]

Published in Coding Computers and IT 开始

Comments

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据